package cn.anosi.controller;


import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.anosi.entity.auth.User;
import cn.anosi.utils.CreateImageCode;

@Controller
public class LoginController extends BaseController {

	@RequestMapping(value="/login", method=RequestMethod.GET)
	public String login(){
		return "login";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST, produces="text/html;charset=utf-8")
	public String login(HttpServletRequest request, User user, Model model) throws Exception {
		/**
		 * 验证码校验
		 */
		String randomcode = request.getParameter("validateCode");
		HttpSession session = request.getSession();
		String validateCode = (String) session.getAttribute("validateCode");
		
		if (randomcode!=null && validateCode!=null) {
			if (!randomcode.equals(validateCode)) {
				model.addAttribute("msg", "验证码错误");
				return "login";
			}
		}
		
		/**
		 * 认证
		 */
		Subject subject = SecurityUtils.getSubject();
		
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
		try {
			subject.login(token);
			if (subject.isAuthenticated()) {
				return "redirect:/index";
			}
		} catch (Exception e) {
			request.setAttribute("shiroLoginFailure", e.getClass().getName());
		}

		/**
		 * 异常信息返回
		 */
		// shiro在认证过程中出现错误后将异常类路径通过request返回
		String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
		if (exceptionClassName != null) {
			if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
				model.addAttribute("msg", "用户名/密码错误");
			} else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
				model.addAttribute("msg", "用户名/密码错误");
			} else if ("validateCodeError".equals(exceptionClassName)) {
				model.addAttribute("msg", "验证码错误");
			} else {
				throw new Exception();// 最终在异常处理器生成未知错误
			}
		}
		
		return "login";
	}
	
	/**
	 * 验证码
	 * @param response
	 * @param session
	 * @throws IOException
	 */
	@RequestMapping(value="/captcha", method=RequestMethod.GET)
	public void captcha(HttpServletResponse response, HttpSession session) throws IOException{
	
		// 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        //禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        
        CreateImageCode vCode = new CreateImageCode(95,32,4,10);
        session.setAttribute("validateCode", vCode.getCode());
        vCode.write(response.getOutputStream());
	}
}
